﻿using Demo.PetaPoco.Application.Dtos;
using Demo.PetaPoco.Application.Dtos.Common;
using Demo.PetaPoco.Application.Extensions;
using PmSoft.FormSchema;
using Demo.PetaPoco.Application.Services.Area;
using Demo.PetaPoco.Application.Services.Config;
using Microsoft.AspNetCore.Mvc;
using PmSoft.Web.Abstractions;
using PmSoft.Web.Abstractions.Captcha;
using System.Reflection;
using PmSoft.FormSchema.Configs;

namespace Demo.PetaPoco.WebApi.Controllers
{
	[Route("api/[controller]")]
	[ApiController]
	public class CommonController(ClickCaptchaService clickCaptchaService,
		CaptchaService captchaService,
		AreaService areaService,
		AppConfigService appConfigService) : ControllerBase
	{
		[HttpGet("clickCaptcha")]
		public async Task<IApiResult> ClickCaptchaAsync(string id)
		{
			var captchaData = await clickCaptchaService.CreateAsync(id);
			return ApiResult.Ok(captchaData);
		}

		[HttpPost("checkClickCaptcha")]
		public async Task<IApiResult> CheckClickCaptchaAsync(CheckClickCaptchaIn dto)
		{
			var ret = await clickCaptchaService.CheckAsync(dto.Id, dto.Info, dto.Unset);
			return ret ? ApiResult.Ok(ret) : ApiResult.Error(ret);
		}

		[HttpGet("captcha")]
		public async Task<IActionResult> CaptchaAsync(string id)
		{
			var data = await captchaService.GenerateImageAsync(id);
			return File(data, "image/png");
		}

		[HttpGet("checkCaptcha")]
		public async Task<IApiResult> CheckCaptchaAsync(string code, string id)
		{
			var ret = await captchaService.CheckAsync(code, id);
			return ret ? ApiResult.Ok(ret) : ApiResult.Error(ret);
		}


		[HttpGet("appConfig")]
		public async Task<IApiResult> GetAppConfigAsync()
		{
			var appConfig = await appConfigService.GetAsync();
			return ApiResult.Ok(appConfig);
		}

		[HttpGet("form-schema")]
		public IApiResult GetFormSchema(string formName)
		{
			var formSchemaResponse = FormSchemaGenerator.GenerateSchema(formName, 
				assembly: Assembly.GetAssembly(typeof(PageQuery)),
				props: new FormProps { WrapperClass= "grid-cols-2" });
			return ApiResult.Ok(formSchemaResponse);
		}

		[HttpGet("area-options")]
		public async Task<IApiResult> AreaOptions()
		{
			var areaDtos = await areaService.GetTopLevelAreasWithChildrenAsync();
			return ApiResult.Ok(areaDtos.ToOptionItems());
		}

		[HttpGet("area-children")]
		public async Task<IApiResult> GetAreaChildrenAsync(int parentId)
		{
			var children = await areaService.GetChildrenAsOptionItemsAsync(parentId);
			return ApiResult.Ok(children);
		}

	}
}
